<template>
  <div class="scheme">
    <div class="scheme-content">
      <div class="scheme-title">
        <span>方案预览</span>
        <span @click="maximize"><SvgIcon name="quanping" /></span>
      </div>
      <el-scrollbar>
        <!-- <div class="scheme-cot">
          <iframe :src="srcUrl" width="100%" height="100%" frameborder="0" v-if="office.includes(activeItem.suffix)">
            这是嵌入 <a target="_blank" href="https://office.com">Microsoft Office</a> 文档，由<a
              target="_blank"
              href="https://office.com/webapps"
              >Office</a
            >
            提供支持。
          </iframe>
          <div style="width: 100%; height: 100%" v-else-if="['pdf'].includes(activeItem.suffix)">
            <embed :src="activeItem.previewLink" style="width: 100%; height: 100%" :key="activeItem.previewLink" />
          </div>
          <div class="preview-stop" v-else-if="activeItem">
            <span>{{ activeItem.originalFileName }}暂不支持预览</span>
            <span @click="downFilesOpen(activeItem.previewLink, activeItem.originalFileName)">下载</span>
          </div>
          <div v-else>
            <el-empty />
          </div>
        </div> -->
        <div class="scheme-cot" :class="{ 'scheme-cot-maximize': maximizeStatus }">
          <div style="width: 100%; height: 100%" v-show="office.includes(activeItem.suffix)">
            <!-- eslint-disable -->
            <r-preview id="preview" :src="activeItem.previewLink" :closeable="'false'" :isContain="'true'"></r-preview>
            <!-- eslint-enable -->
          </div>
          <div class="preview-stop" v-show="!office.includes(activeItem.suffix) && activeItem">
            <span>{{ activeItem.originalFileName }}暂不支持预览</span>
            <span @click="downFilesOpen(activeItem.path, activeItem.originalFileName)">下载</span>
          </div>
          <div v-show="!office.includes(activeItem.suffix) && !activeItem">
            <el-empty />
          </div>
          <div class="close-maximize" @click="() => (maximizeStatus = false)">
            <el-icon><CircleClose /></el-icon>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="scheme-right">
      <div class="scheme-file">
        <div class="scheme-file-title">
          <span>方案文件</span>
          <span @click="addProjectPlanFn"><SvgIcon name="tianjia" /></span>
        </div>
        <el-scrollbar>
          <ul class="scheme-file-list" v-if="planList.length">
            <li
              v-for="(item, index) in planList"
              :key="index"
              :class="{ active: item.isActive }"
              @click="
                () => {
                  activePlanFn(item);
                }
              "
            >
              <span class="img"> <SvgIcon name="wendang" /></span>
              <p>
                <span>{{ item.originalFileName }}</span>
                <span>
                  <i>{{ item.createByName }} 上传于 {{ dayJs(item.gmtCreate).format("YYYY年MM月DD日") }}</i>
                  <i
                    @click="
                      () => {
                        delPlanFn(item);
                      }
                    "
                  >
                    删除
                  </i>
                </span>
              </p>
            </li>
          </ul>
          <div v-else>
            <el-empty />
          </div>
        </el-scrollbar>
      </div>
      <div class="scheme-file">
        <div class="scheme-file-title">
          <span>方案历史</span>
        </div>
        <el-scrollbar>
          <ul class="scheme-file-list" v-if="planHistoryList.length">
            <li
              v-for="(item, index) in planHistoryList"
              :key="index"
              :class="{ active: item.isActive }"
              @click="
                () => {
                  activePlanHistoryFn(item);
                }
              "
            >
              <span class="img"> <SvgIcon name="wendang" /></span>
              <p>
                <span>{{ item.originalFileName }}</span>
                <span>
                  <i>{{ item.createByName }} 上传于 {{ dayJs(item.gmtCreate).format("YYYY年MM月DD日") }}</i>
                  <i></i>
                  <!-- <i
                    @click="
                      () => {
                        delPlanFn(item);
                      }
                    "
                  >
                    删除
                  </i> -->
                </span>
              </p>
            </li>
          </ul>
          <div v-else>
            <el-empty />
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
  <div v-if="drawerVisible">
    <Dialog v-model:drawerVisible="drawerVisible" v-model:config="config" :project-id="projectId" @change="refresh" />
  </div>
</template>
<script setup lang="ts">
import "@randevcx/ranui";
import { ref, inject, onMounted } from "vue";
// import { useGlobalStore } from "@/stores/modules/global";
import {
  getListProjectPlan,
  deletePlan,
  getListProjectPlanHistory,
  addProjectPlan,
  getProjectPlanDetail
} from "@/api/modules/project";
import dayJs from "dayjs";
import Dialog from "../components/Dialog.vue";
import { PROJECT } from "@/constants";
import { downFilesOpen } from "@/utils/index";
// const globalStore = useGlobalStore();
// inject
const projectId = inject("projectId", ref(""));
/**hook */
import { useHandleData } from "@/hooks/useHandleData";
import { useDict } from "@/hooks/useDict";
const { getDict } = useDict(["fileTypeId"]);
//变量
const planList = ref([]);
const planHistoryList = ref([]);
const activeItem = ref("");
const srcUrl = ref("");
const office = ref(["docx", "xlsx", "pptx", "doc", "xls", "ppt", "pdf"]);
let drawerVisible = ref(false);
let config = ref<any>({
  width: 24
});
const maximizeStatus = ref(false);
// 方法
const getListProjectPlanFn = async () => {
  try {
    const { data } = await getListProjectPlan({ projectId });
    planList.value =
      (data &&
        data.map((item, index) => {
          item.isActive = activeItem.value ? activeItem.value.id === item.id : index === 0;
          return item;
        })) ||
      [];
    if (planList.value.length && !activeItem.value) {
      getProjectPlanDetailFn(planList.value[0].id);
    }
  } catch (e) {
    console.log(e);
  }
};
const getListProjectPlanHistoryFn = async () => {
  try {
    const { data } = await getListProjectPlanHistory({ projectId });
    planHistoryList.value =
      (data &&
        data.map(item => {
          item.isActive = activeItem.value ? activeItem.value.id === item.id : false;
          return item;
        })) ||
      [];
  } catch (e) {
    console.log(e);
  }
};
const activePlanFn = data => {
  planList.value = planList.value.map(item => {
    item.isActive = data.id === item.id;
    return item;
  });
  planHistoryList.value = planHistoryList.value.map(item => {
    item.isActive = false;
    return item;
  });
  getProjectPlanDetailFn(data.id);
};
const activePlanHistoryFn = data => {
  planHistoryList.value = planHistoryList.value.map(item => {
    item.isActive = data.id === item.id;
    return item;
  });
  planList.value = planList.value.map(item => {
    item.isActive = false;
    return item;
  });
  getProjectPlanDetailFn(data.id);
};
const delPlanFn = async item => {
  await useHandleData(deletePlan, { id: item.id }, `删除【${item.originalFileName}】`);
  refresh();
};
const refresh = () => {
  activeItem.value = "";
  getListProjectPlanFn();
  getListProjectPlanHistoryFn();
};
const addProjectPlanFn = () => {
  drawerVisible.value = true;
  drawerVisible.value = true;
  config.value.title = "添加方案文件";
  config.value.form = {
    formData: {
      projectId,
      typeId: "",
      file: []
    },
    rules: {
      typeId: [{ required: true, message: "请选择方案文件类型" }],
      file: [{ required: true, message: "请上传方案文件" }]
    }
  };
  config.value.column = [
    {
      type: "select",
      key: "typeId",
      formItemAttribute: {
        label: "方案文件类型"
      },
      attributes: {
        placeholder: "请选择方案文件类型",
        options: getDict("fileTypeId"),
        multiple: false,
        filterable: true,
        clearable: true
      }
    },
    {
      type: "file",
      key: "file",
      formItemAttribute: {
        label: "上传方案文件"
      },
      attributes: {
        "prefix-data": PROJECT,
        multiple: false,
        showFileList: true,
        limit: 1
        // change: data => {
        //   data.file = data;
        // }
      }
    }
  ];
  config.value.api = addProjectPlan;
  config.value.transformData = data => {
    if (data && data.file.length) {
      data.name = data.file[0].name;
      data.path = data.file[0].path;
      data.originalFileName = data.file[0].originalFileName;
      delete data.file;
    }
    return data;
  };
  config.value.message = "添加成功";
};
const getProjectPlanDetailFn = async id => {
  try {
    const { data } = await getProjectPlanDetail({ id });
    // alert(decodeURIComponent(data.previewLink));
    // 添加后缀名
    const suffix = data.path.split(".");
    data.suffix = suffix[suffix.length - 1];
    // alert(data.suffix);
    // data.previewLink =
    //   "https://501351981.github.io/vue-office/examples/dist/static/test-files/test.pdf?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=KYIRtWKFzRUlMWzx50mz/20240528/us-east-1/s3/aws4_request&X-Amz-Date=20240528T063315Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=d09ebfe16093b32b673275977a18e718fcf45b98f768fd6244656f3dba961055";
    if (office.value.includes(data.suffix)) {
      srcUrl.value =
        "https://view.officeapps.live.com/op/embed.aspx?src=" + encodeURIComponent(decodeURIComponent(data.previewLink));
    }
    activeItem.value = data;
    // alert(decodeURIComponent(data.previewLink));
    // console.log(data);
  } catch (e) {
    console.log(e);
  }
};
// 当前页全屏
const maximize = () => {
  maximizeStatus.value = true;
  // globalStore.setGlobalState("maximize", true);
};
onMounted(() => {
  refresh();
});
</script>
<style scoped lang="scss">
ul,
li {
  padding: 0;
  margin: 0;
  list-style: none;
}
p {
  padding: 0;
  margin: 0;
}
i {
  font-style: normal;
}
.scheme {
  display: flex;
  justify-content: space-between;
  height: 100%;
  .scheme-content {
    flex: 1;
    overflow: hidden;
    .scheme-title {
      display: flex;
      justify-content: space-between;
      height: 60px;
      padding: 0 30px;
      line-height: 60px;
      background: #ffffff;
      border-bottom: 1px solid #f4f4f4;
      span:first-child {
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }
      span:last-child {
        cursor: pointer;
      }
    }
    .scheme-cot {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: center;
      height: 0;
      height: calc(100% - 61px);
      overflow: hidden;

      // height: 1000px;
      background: #ffffff;
      iframe {
        // width: 100%;
        // height: 100%;
        background: #ffffff;
        border: 0;
      }
      #preview {
        --el-loading-color: var(--el-color-primary);
      }
      .preview-stop {
        display: flex;
        flex-flow: column nowrap;
        text-align: center;
        span:first-child {
          color: #e25e72;
        }
        span:last-child {
          margin-top: 10px;
          color: #333333;
          cursor: pointer;
          &:hover {
            color: $primary-color;
          }
        }
      }
    }
    .scheme-cot-maximize {
      position: fixed;
      top: 0;
      left: 0;
      z-index: 1000000;
      display: block;
      width: 100%;
      height: 100%;
      background: #ffffff;
      .close-maximize {
        display: block;
      }
    }
    .close-maximize {
      position: fixed;
      top: 10px;
      right: 40px;
      z-index: 1000001;
      display: none;
      width: 30px;
      height: 30px;
      font-size: 16px;
      line-height: 30px;
      color: #333333;
      text-align: center;
      cursor: pointer;
    }
  }
  .scheme-right {
    box-sizing: border-box;
    display: grid;
    flex: 0 0 370px;
    grid-template-rows: 1fr 1fr;
    grid-row-gap: 10px;
    margin-left: 10px;
    overflow: hidden;
    .scheme-file {
      display: flex;
      flex: 1;
      flex-flow: column nowrap;
      overflow: hidden;
      background: #ffffff;
      .scheme-file-title {
        box-sizing: border-box;
        display: flex;
        flex: 0 0 60px;
        align-items: center;
        justify-content: space-between;
        padding: 0 30px;
        border-bottom: 1px solid #f4f4f4;
        span:first-child {
          font-size: 16px;
          font-weight: 600;
          color: #333333;
        }
        span:last-child {
          color: #666666;
          cursor: pointer;
        }
      }
      .scheme-file-list {
        box-sizing: border-box;
        display: flex;
        flex: 1;
        flex-flow: column nowrap;
        height: 0;
        padding: 14px;
        li {
          display: flex;
          align-items: center;
          height: 50px;
          padding: 6px 20px;
          cursor: pointer;
          border-radius: 4px;
          .img {
            width: 22px;
            height: 24px;
            margin-right: 10px;
          }
          p {
            display: flex;
            flex: 1;
            flex-flow: column nowrap;
            justify-content: center;
            overflow: hidden;
            span:first-child {
              margin-bottom: 4px;
              overflow: hidden;
              font-size: 14px;
              font-weight: 400;
              color: #333333;
              text-overflow: ellipsis;
            }
            span:last-child {
              display: flex;
              justify-content: space-between;
              font-size: 12px;
              font-weight: 400;
              color: #999999;
              i:last-child {
                font-size: 12px;
                font-weight: 400;
                color: #e25e72;
                cursor: pointer;
              }
              .color {
                color: #5378f6 !important;
              }
            }
          }
        }
        .active {
          background: #f4f4f4;
        }
      }
    }
  }
}
</style>
